<?php

namespace app\index\model;

use think\facade\Session;
use think\Model;

class Sign extends Model
{
    public  function userInfo()
    {
        return $this->hasOne(User::class , 'id' , 'user_id');
    }
    // 连续签到奖励的积分数量
    public static function rule($day)
    {
        if($day < 3) return 5;
        else if($day < 7) return 15;
        else if($day < 15) return 20;
        else return 30;
    }
    // 得到签到消息
    public static function get()
    {
        $uid = Session::get('user.user_id');
        $sign = self::where('user_id',$uid);
        if($sign->findOrEmpty()->isEmpty()){
            self::create(['user_id' => $uid ,'day' => 0,'sign_time' => 0]);
        }
        return $sign->find();
        
    }
    public static function do()
    {
        $uid = Session::get('user.user_id');
        $isSign = self::where('user_id',$uid);
        // 初次签到
        if($isSign->findOrEmpty()->isEmpty()){
            self::create(['user_id' => $uid ,'day' => 1,'sign_time' => time()]);
        }else{
            $sign = $isSign->find();
            $signTime = $sign->sign_time;
            if(date('d',time()) == date('d',$signTime))
            {
                return '每天只能签到一次哦！';
            }else if( date('d',strtotime('-1 day')) == date('d',$signTime))
            {
                $isSign->update(['sign_time' => time() , 'day' => $sign->day + 1]);
            }else{
                $isSign->update(['sign_time' => time() , 'day' => 1]);
            }
        }
        return 1;
    }
    // 判断是否签到
    public static function isSign()
    {
        $uid = Session::get('user.user_id');
        $isSign = self::where('user_id',$uid)->find();
        if(date('d',time()) == date('d',$isSign->sign_time)) return 1;
        return 0;
    }
    // 最快签到列表
    public static function newSignLis()
    {
        $list = self::with(['userInfo' => function($query){
            $query->field('id ,username , head_icon');
        }])->whereDay('sign_time')->order('id desc')->limit(20)->select();
        return $list;
    }
    // 今日签到最快列表
    public static function todayFastLis()
    {
        $list = self::with(['userInfo' => function($query){
            $query->field('id ,username , head_icon');
        }])->whereDay('sign_time')->order('sign_time asc')->limit(20)->select();
        return $list;
    }
    // 总签到榜 以连续签到最多为主
    public static function totalLis()
    {
        $list = self::with(['userInfo' => function($query){
            $query->field('id ,username , head_icon');
        }])->order('day desc')->limit(20)->select();
        return $list;
    }
}
